<script setup lang="ts">
import {ElMessage} from 'element-plus'
import {reactive, onMounted, ref} from "vue";

import type {FormInstance,} from 'element-plus'

import {loginSelectBiz, loginHandle} from '@/dt-lib/plug/api/open/login'
import {useAdminStore} from '@/dt-lib/plug/pinia/stores/admin'
import {useRouter} from 'vue-router'

import {ElNotification} from 'element-plus'

const adminStore = useAdminStore()
const router = useRouter()

const loginFormRef = ref<FormInstance>()

onMounted(() => {

  if (import.meta.env.MODE === 'development') {
    ruleForm.account = '18144132417'
    ruleForm.password = 'ABFamiay#%999'
  }

})

const butLoading = ref(false)

const loginStep = ref(2)

const goBack = () => {
  console.log('goBack')
  loginStep.value = 2
}

interface FormState {
  account: string;
  password: string;
  remember: boolean;
}

const ruleForm = reactive<FormState>({
  account: '',
  password: '',
  remember: true,
});

interface BizItem {
  user_id: number;
  base_id: number;
  group_id: number;
  biz_id: number;
  group_name: string;
  biz_name: string;
}

const bizs = ref<BizItem[]>([]);
const selectBizId = ref(0);

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {

      butLoading.value = true

      const postData = {
        account: ruleForm.account
      }

      loginSelectBiz(postData).then(res => {

        bizs.value = res.data

        // 只有一个组织时直接登陆
        if (bizs.value.length === 1) {
          return selectBiz(bizs.value[0])
        }

        loginStep.value = 3


      }).catch(error => {
        console.log(error)
      }).finally(() => {
        butLoading.value = false
        selectBizId.value = 0
      })


    } else {
      console.log('error submit!', fields)
    }
  })
}


const selectBiz = (biz: BizItem) => {

  selectBizId.value = biz.biz_id

  const postData = {
    base_id: biz.base_id,
    user_id: biz.user_id,
    password: ruleForm.password
  }

  // console.log('postData')
  //
  // return;

  loginHandle(postData).then(res => {

    ElNotification({
      type: 'success',
      title: '登陆成功',
      message: '欢迎回来：' + res.data.user_name + '，又是美好的一天开始啦！',
      duration: 2000
    });

    adminStore.setAdmin(res.data)
    router.push('/home')

  }).catch(error => {
    // console.log(error)
  }).finally(() => {
    // console.log('finally')
    setTimeout(() => {
      butLoading.value = false
      selectBizId.value = 0
    }, 800)

  })


}


</script>

<template>
  <div class="login-cont">
    <el-row style="height: 100%" justify="center" align="middle">
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="my-h-100 my-bg-fff">
        <div class="my-flex my-align-items-center my-justify-content-center my-flex-direction-column my-h-100">
          <transition name="fade" mode="out-in" appear>
            <template v-if="loginStep==2">
              <div class="login-step-one" key="login-step-one">
                <div style="padding: 0 30px 30px 30px">
                  <h1>欢迎使用创世纪系统</h1>
                  <h4>
                    <el-text class="mx-1" type="info">CRM系统，AD系统，OA系统，DMS系统</el-text>
                  </h4>
                </div>
                <el-row style="padding: 0 30px">
                  <el-col :xs="24" :sm="8" style="text-align: center">
                    <el-button round class="my-media-w-100" @click="ElMessage({ message: '开发中',type: 'warning',});">
                      <DingdingOutlined style="padding-right: 5px"/>
                      钉钉登陆
                    </el-button>
                  </el-col>
                  <el-col :xs="24" :sm="8" style="text-align: center">
                    <el-button round class="my-media-w-100" @click="ElMessage({ message: '开发中',type: 'warning',});">
                      <WechatOutlined style="padding-right: 5px"/>
                      微信登陆
                    </el-button>
                  </el-col>
                  <el-col :xs="24" :sm="8" style="text-align: center">
                    <el-button round class="my-media-w-100 my-l-last"
                               @click="ElMessage({ message: '开发中',type: 'warning',});">
                      <MobileOutlined style="padding-right: 5px"/>
                      短信登陆
                    </el-button>
                  </el-col>
                  <el-divider style="font-size:14px;color: #3A4752; margin: 30px 0">密码登陆</el-divider>
                </el-row>


                <el-form class="form" :model="ruleForm" ref="loginFormRef">

                  <el-form-item prop="account"
                                :rules="[{ required: true, message: '请输入你的账号' }]">
                    <MyFormItem title="账号" size="large" block>
                      <el-input clearable autofocus v-model="ruleForm.account" placeholder="请输入你的账号"/>
                    </MyFormItem>
                  </el-form-item>

                  <el-form-item prop="password" :rules="[{ required: true, message: '请输入你的密码' }]">
                    <MyFormItem title="密码" size="large" block>
                      <el-input type="password" clearable show-password v-model="ruleForm.password"
                                placeholder="请输入你的密码"/>
                    </MyFormItem>
                  </el-form-item>

                  <el-form-item>
                    <el-row style="width: 100%">
                      <el-col :span="12">
                        <el-checkbox v-model="ruleForm.remember">记住我</el-checkbox>
                      </el-col>
                      <el-col :span="12" style="text-align: right">
                        <a class="login-form-forgot" href="javascript:void(0);"
                           @click="ElMessage({ message: '开发中',type: 'warning',});">忘记密码?</a>
                      </el-col>
                    </el-row>
                  </el-form-item>

                  <el-form-item>
                    <el-button type="primary" class="my-w-100" size="large" @click="submitForm(loginFormRef)"
                               :loading="butLoading">登陆
                    </el-button>
                  </el-form-item>

                  <el-form-item>
                    <el-row style="width: 100%;text-align: center">
                      <el-col :span="24">
                        <el-text class="mx-1" type="info">没有账号？<a href="javascript:void(0);"
                                                                      @click="ElMessage({ message: '开发中',type: 'warning',});">创建一个账号！</a>审核后即可登陆

                        </el-text>
                      </el-col>
                    </el-row>
                  </el-form-item>

                </el-form>

              </div>
            </template>
            <template v-else>
              <div class="login-step-two" key="login-step-two">
                <div style="padding: 0 30px 30px 30px">
                  <h1>选择你要进入的组织</h1>
                  <h4>
                    <el-text class="mx-1" type="info">以下组织下有你的账号</el-text>
                  </h4>
                </div>
                <div class="biz-list">
                  <div class="biz" v-loading="selectBizId==biz.biz_id"
                       :class="{'disable':selectBizId}" v-for="biz in bizs"
                       :key="biz.base_id"
                       @click="selectBiz(biz)">
                    <div class="biz-logo">
                      <div class="no-image">
                        <el-icon>
                          <OfficeBuilding/>
                        </el-icon>
                      </div>
                    </div>
                    <div class="biz-info">
                      <div class="left">
                        <div class="group-name">
                          <el-text>{{ biz.group_name }}</el-text>
                        </div>
                        <div class="biz-name">
                          <el-text type="info">{{ biz.biz_name }}</el-text>
                        </div>
                      </div>
                      <div class="right">
                        <el-icon>
                          <ArrowRight/>
                        </el-icon>
                      </div>
                    </div>
                  </div>

                </div>
                <div class="goback">
                  <el-button round style="width: 100%" @click="goBack" :disabled="selectBizId>0">返回</el-button>
                </div>
              </div>
            </template>
          </transition>

        </div>
      </el-col>
      <el-col :xs="0" :sm="0" :md="0" :lg="12" :xl="12">
        <div class="my-flex my-align-items-center my-justify-content-center my-h-100"><img
            src="@/dt-lib/assets/images/user-login.png" class="login-company-image"></div>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">

.login-step-one, .login-step-two {
  width: 450px;
}

.biz-list {
  display: flex;
  flex-direction: column;
  padding: 0 30px 10px 30px;
  max-height: 450px;
  overflow-y: auto;

  .biz {



    display: flex;
    align-items: center;

    cursor: pointer;

    padding: 10px;
    background-color: var(--app-nav-color-1);
    border-radius: 10px;
    margin-bottom: 10px;
    transition: all .3s ease-in-out;

    &:hover {

      background-color: var(--app-nav-color);

      .el-text {
        color: #fff;
      }


      .el-icon {
        color: #fff;
      }

    }

    .biz-logo {
      .no-image {
        display: flex;
        align-items: center;
        justify-content: center;

        color: #fff;
        font-size: 28px;

        width: 50px;
        height: 50px;
        background-color: #888;
        border-radius: 5px;
      }
    }


    .biz-info {
      padding-left: 10px;
      flex: auto;

      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
      }

      .right {
        text-align: right;
        width: 20px;
      }
    }

  }


}

.goback {
  width: 50%;
  margin: 0 auto;
  padding: 0 30px;
}

.login-cont {
  width: 100%;
  height: 100%;


}

.login-form-forgot {
  float: right;
}

.login-company-image {
  transition: width .3s ease-in-out;
}

@media (max-width: 1300px) {
  .login-company-image {
    width: 90%;
  }
}

@media (max-width: 768px) {

  .my-media-w-100 {
    width: 100% !important;
    margin-bottom: 10px;
  }

  .my-l-last {
    margin-bottom: 0 !important;
  }

}

@media (max-width: 520px) {

  .login-step-one, .login-step-two {
    width: 95%;

    h1 {
      font-size: 24px;
    }
  }


}


.form {
  width: 100%;
  padding: 0px 30px;
}
</style>